package com.yaorange.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yaorange.dao.RoleMapper;
import com.yaorange.entity.Role;
import com.yaorange.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;


@Service
@Transactional//事务相关
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;


    //分页（带模糊查询）
    @Override
    public PageInfo<Role> getPageByCondition(Integer pageNum, Integer pageSize, String conditionRoleName) {

        PageHelper.startPage(pageNum,pageSize);
        //设置查询条件
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        //搜索用户名
        if(conditionRoleName != null && !"".equals(conditionRoleName)){
            criteria.andLike("roleName","%"+conditionRoleName+"%");
        }
        //不查询为1的信息（被删除了的）
        criteria.andNotEqualTo("roleState",1);

        List<Role> roles = roleMapper.selectByExample(example);
        //组装返回PageInfo
        return new PageInfo<>(roles);
    }


    //新增
    @Override
    public int addRole(Role role) {
        int insert = roleMapper.insert(role);
        return insert;
    }


    //删除时，查询是否存在该角色
    @Override
    public Role getRole(Integer roleId) {
        Role role = roleMapper.selectByPrimaryKey(roleId);
        return role;
    }

    //删除时设置状态用
    @Override
    public int updateRole(Role role) {
        int i = roleMapper.updateByPrimaryKeySelective(role);
        return i;
    }

    @Override
    public List<Role> getList() {
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("roleState",1);//不要删除的（-1）
        return roleMapper.selectByExample(example);
    }

    @Override
    public List<Integer> getModuleIds(Integer roleId) {
        return roleMapper.selectModuleIdsByRoleId(roleId);
    }

    @Override
    public int updateModules(Integer roleId, List<Integer> moduleIds) {
        //基于中间表的操作思路
        //1:先删除当前角色在中间表的所有数据
        roleMapper.deleteModuleIdsByRoleId(roleId);
        //2:判断是否勾选数据，再新增当前角色和模块的关联数据
        int rows = 0;
        if(moduleIds != null && moduleIds.size() > 0){
            rows = roleMapper.insertModuleIds(roleId,moduleIds);
        }
        return rows;
    }
}
